import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/mine/task_center_data.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';

import '../../../tools_base/loading/LoadingHelper.dart';
import 'integral_record_logic.dart';

class IntegralExchangeVipView extends StatefulWidget {
  const IntegralExchangeVipView({super.key});

  @override
  State<IntegralExchangeVipView> createState() => _IntegralExchangeViewVipState();
}

class _IntegralExchangeViewVipState extends State<IntegralExchangeVipView> {
  final dataSouce = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final res = await MineService.fetchIntegralExchangeList();
      globalStore.refreshWallet();
      if (res.isNotEmpty) {
        late List list = [];
        res.forEach((element) {
          if (element.type == 1) {
            list.add(element);
          }
        });
        dataSouce.addAll(list);
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    double ratio = ((MediaQuery.sizeOf(context).width- 60)/3) /158;

    if (dataSouce.isEmpty) return SizedBox.shrink();
    return Column(
      children: [
        GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, crossAxisSpacing: 16, mainAxisSpacing: 14, childAspectRatio: ratio),
          itemCount: dataSouce.length,
          itemBuilder: (BuildContext context, int index) {
            final model = dataSouce[index];
            return SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    decoration: BoxDecoration(color: Color(0x1AFFFFFF), borderRadius: BorderRadius.circular(6)),
                    padding: EdgeInsets.only(left: 8.w, right: 8.w, top: 16.h, bottom: 16.h),
                    child: Column(
                      children: [
                        Image.asset(
                          'vip_integral.png'.mineImgPath,
                          width: 30,
                          fit: BoxFit.fitWidth,
                          color: AppColors.actionRed,
                        ),
                        10.sizeBoxH,
                        Text(
                          '${globalStore.wallet?.integral ?? 0}积分',
                          style: TextStyle(color: Color(0xE5FFFFFF), fontSize: 16),
                        ),
                        10.sizeBoxH,
                        Container(
                          width: 60,
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(horizontal: 0, vertical: 2),
                          decoration: BoxDecoration(color: Color(0xffFFD5A8), borderRadius: BorderRadius.circular(2)),
                          child: Text(
                            '${model.name ?? ""}',
                            style: TextStyle(color: Color(0xFF692A1F), fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                  ),
                  10.sizeBoxH,
                  GestureDetector(
                    onTap: () => onExchange(model),
                    child: Container(
                      width: 60,
                      height: 20,
                      alignment: Alignment.center,
                      padding: EdgeInsets.symmetric(horizontal: 0, vertical: 2),
                      decoration: BoxDecoration(color: AppColors.actionRed, borderRadius: BorderRadius.circular(2)),
                      child: Text(
                        '兑换',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                  )
                ],
              ),
            );
          },
        ),
        20.sizeBoxH,
        Divider(
          height: 1,
          color: Colors.white.withOpacity(.1),
        )
      ],
    );
  }

  onExchange(IntegralExchangeModel model) async {
    final hasIntegral = globalStore.wallet?.integral ?? 0;
    if (hasIntegral < (model.price ?? 0)) {
      showToast('积分不足，无法兑换～');
      return;
    }
    LoadingHelper.showLoading();
    final res = await MineService.integralExchangeSomething(model.id ?? '');
    LoadingHelper.dismissLoading();
    if (res) {
      showToast('兑换成功～');
      IntegralRecordLogic logic = Get.find<IntegralRecordLogic>();
      logic.loadData(page: 1);
      globalStore.refreshWallet();
    }
  }
}
